package com.xp.basic.heima.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TestSingleThreadNio {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //非阻塞
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));

        List<SocketChannel>  channels = new ArrayList<>(10);
        while (true){
//            System.out.println(" connecting ...");
            SocketChannel sc = ssc.accept();

            if (Objects.nonNull(sc)) {
                //设置为非阻塞
                sc.configureBlocking(false);
                System.out.println(" connected : "+ sc);

                channels.add(sc);
            }

            for (SocketChannel channel : channels) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(10);

//                System.out.println(" wait reading ..... ");
                int read = channel.read(byteBuffer);
                if (read > 0) {
                    //这是个重要的东西，需要翻转
                    byteBuffer.flip();
                    System.out.println(" read : "+read+" byte "+" byteBuffer : "+ byteBuffer.remaining());
                    byte[] bytes = new byte[read];
                    byteBuffer.get(bytes);

                    String msg = new String(bytes);
                    System.out.println("收到客户端："+ channel.getRemoteAddress().toString()+" 消息："+msg);
                }


            }
        }

    }
}
